package com.xincheng.shuimalong.fragment.home;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bumptech.glide.request.RequestOptions;
import com.xincheng.library.util.CommonUtil;
import com.xincheng.library.util.PrefUtil;
import com.xincheng.library.util.UIUtil;
import com.xincheng.library.widget.alertview.AlertView;
import com.xincheng.library.widget.alertview.OnAlertItemClickListener;
import com.xincheng.library.xlog.XLog;
import com.xincheng.library.xswipemenurecyclerview.Mode;
import com.xincheng.library.xswipemenurecyclerview.holder.RecyclerHolder;
import com.xincheng.library.xswipemenurecyclerview.listener.OnItemClickListener;
import com.xincheng.library.xswipemenurecyclerview.listener.OnLoadingListener;
import com.xincheng.library.xswipemenurecyclerview.recycler.XRecyclerView;
import com.xincheng.library.xswipemenurecyclerview.widget.ProgressStyle;
import com.xincheng.shuimalong.R;
import com.xincheng.shuimalong.activity.EvaluateActivity;
import com.xincheng.shuimalong.activity.MainActivity;
import com.xincheng.shuimalong.activity.OrderDetailActivity;
import com.xincheng.shuimalong.activity.insurance.UserHomeActivity;
import com.xincheng.shuimalong.activity.recept.ReceiptBackActivity;
import com.xincheng.shuimalong.activity.recept.ReceiptIssueActivity;
import com.xincheng.shuimalong.activity.sell.PayOrderActivity;
import com.xincheng.shuimalong.activity.sell.SellReceiptActivity;
import com.xincheng.shuimalong.adapter.OrderAdapter;
import com.xincheng.shuimalong.api.AppUrl;
import com.xincheng.shuimalong.api.BaseObserver;
import com.xincheng.shuimalong.api.GetParam;
import com.xincheng.shuimalong.api.PostParam;
import com.xincheng.shuimalong.api.RetroSubscrube;
import com.xincheng.shuimalong.common.Constant;
import com.xincheng.shuimalong.common.IntentKey;
import com.xincheng.shuimalong.common.OrderConfig;
import com.xincheng.shuimalong.common.PrefKey;
import com.xincheng.shuimalong.common.RefreshStatus;
import com.xincheng.shuimalong.common.RequestCodeKey;
import com.xincheng.shuimalong.entity.Order;
import com.xincheng.shuimalong.entity.OrderDetail;
import com.xincheng.shuimalong.entity.config.CommonConfig;
import com.xincheng.shuimalong.entity.config.RegionData;
import com.xincheng.shuimalong.fragment.BaseFragment;
import com.xincheng.shuimalong.listener.ItemButtonClickListener;
import com.xincheng.shuimalong.manager.GlideOptionsManager;
import com.xincheng.shuimalong.util.GsonUtil;
import com.xincheng.shuimalong.util.MyUtil;
import com.xincheng.shuimalong.util.ShowActivity;
import com.xincheng.shuimalong.view.CardItemDecoration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

/**
 * Created by xiaote on 2017/6/29.
 */

public class OrderFragment extends BaseFragment {

    @BindView(R.id.home_list_mrv)
    XRecyclerView mQuoteListRv;

    private ThreadLocal<List<Order.Data>> mOrderList = new ThreadLocal<>();
    private OrderAdapter mAdapter;
    private RefreshStatus mRefreshStatus;
    private int mPage;
    private String mToken;
    private int mOrderConfig;

    private int mStatus;
    private int mFileStatus;
    private int mToComment;
    private String mStatusName = "";
    private boolean mIsCreate;
    private int mCityId;
    private int mProvinceId;
    private String mKeyword;

    @Override
    public int getFragmentLayoutId() {
        return R.layout.fragment_home_list;
    }

    @Override
    public void initData() {
        mQuoteListRv = UIUtil.findViewById(mRootView, R.id.home_list_mrv);
        mToken = PrefUtil.getString(getActivity(), PrefKey.TOKEN, "");
        mRefreshStatus = RefreshStatus.LOAD_DEFAULT;
        mPage = 1;
        mStatusName = "";
        Bundle extras = getArguments();
        mOrderConfig = extras.getInt(IntentKey.ORDER_CONFIG);
        mState = extras.getInt(IntentKey.STATE);
        mProvinceId = ((MainActivity) getActivity()).getProvinceId();
        if (mProvinceId == 0) {
            mProvinceId = extras.getInt("provinceId", 0);
        }
        mCityId = ((MainActivity) getActivity()).getCityId();
        if (mCityId == 0) {
            mCityId = extras.getInt("cityId", 0);
        }
        mKeyword = extras.getString("keyword", "");
        XLog.e("state=>" + mState);
        mQuoteListRv.setLayoutManager(new LinearLayoutManager(getActivity()));
        mQuoteListRv.addItemDecoration(new CardItemDecoration());
        mQuoteListRv.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mQuoteListRv.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mQuoteListRv.setArrowImageView(R.drawable.iconfont_downgrey);
        mAdapter = new OrderAdapter(getActivity(), mOrderConfig,
                GlideOptionsManager.getInstance().getRequestOptions());
        mQuoteListRv.setAdapter(mAdapter);
        mQuoteListRv.setMode(Mode.BOTH);
        getOrder();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mIsCreate = true;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (Constant.SUCCESS) {
            Constant.SUCCESS = false;
            getOrder();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && mIsCreate) {
            getOrder();
        }
    }

    @Override
    public void addListener() {
        mQuoteListRv.setOnLoadingListener(new MyOnLoadingListener());
        mQuoteListRv.setOnItemClickListener(new MyOnItemClickListener());
        mAdapter.setItemButtonClickListener(new MyItemButtonClickListener());
    }

    private void initStatus() {
        switch (mState) {
            case 0:
                mStatus = 0;
                mFileStatus = 0;
                mToComment = 0;
                mStatusName = "待报价";
                break;
            case 1:
                mStatus = 1;
                mFileStatus = 0;
                mToComment = 0;
                mStatusName = "待付款";
                break;
            case 2:
                switch (mOrderConfig) {
                    case OrderConfig.RECEIPT:
                        mStatus = 2;
                        mFileStatus = 0;
                        mToComment = 0;
                        mStatusName = "待出单";
                        break;
                    case OrderConfig.SELL:
                        mStatus = 2;
                        mFileStatus = 1;
                        mToComment = 0;
                        mStatusName = "待签收";
                        break;
                }
                break;
            case 3:
                switch (mOrderConfig) {
                    case OrderConfig.RECEIPT:
                        mStatus = 2;
                        mFileStatus = 3;
                        mStatusName = "待回单";
                        mToComment = 0;
                        break;
                    case OrderConfig.SELL:
                        mStatus = 2;
                        mFileStatus = 2;
                        mToComment = 0;
                        mStatusName = "待回单";
                        break;
                }
                break;
            case 4:
                mStatus = 2;
                mFileStatus = 4;
                mToComment = 1;
                mStatusName = "待评价";
                break;
            case 5:
                mStatus = 2;
                mFileStatus = 4;
                mToComment = 1;
                mStatusName = "已完成";
                break;
            case 6:
                mStatus = 0;
                mFileStatus = 0;
                mToComment = 0;
                mStatusName = "已失效";
                break;
        }
    }

    private void getOrder() {
        initStatus();
        BaseObserver observer = new BaseObserver(getActivity()) {
            @Override
            protected void onHandleSuccess(Object data, String msg) {
                try {
                    if (data != null) {
                        if (mQuoteListRv != null) {
                            mQuoteListRv.setMode(Mode.BOTH);
                        }
                        Order order = GsonUtil.parseData(data, Order.class);
                        List<Order.Data> dataList = order.getOrderList();
                        switch (mRefreshStatus) {
                            case LOAD_DEFAULT:
                                mOrderList.set(dataList);
                                break;
                            case PULL_TO_REFRESH:
                                mQuoteListRv.refreshComplete();
                                mOrderList.set(dataList);
                                break;
                            case LOAD_MORE:
                                mQuoteListRv.loadMoreComplete();
                                mOrderList.get().addAll(dataList);
                                break;
                        }
                        if (MyUtil.isDataLengthLess(dataList)) {
                            mQuoteListRv.setMode(Mode.PULL_TO_REFRESH);
                        }
                        mAdapter.refreshData(mOrderList.get());
                    }
                } catch (Exception e) {
                    XLog.e(e.getMessage());
                }
            }
        };
        if (mRefreshStatus == RefreshStatus.LOAD_DEFAULT) {
            observer.initProgressDialog(getActivity(), getString(R.string.loading_data));
        }
        switch (mOrderConfig) {
            case OrderConfig.RECEIPT:
                RetroSubscrube.getInstance().getSubscrube(
                        GetParam.myAcOrder(mToken, mStatus, mFileStatus, mToComment, mStatusName,
                                mCityId, mProvinceId, 0, 0, 0, 0, mKeyword, mPage), observer);
                break;
            case OrderConfig.SELL:
                RetroSubscrube.getInstance().getSubscrube(
                        GetParam.myBillOrder(mToken, mStatus, mFileStatus, mToComment, mStatusName,
                                mCityId, mProvinceId, 0, 0, 0, 0, mKeyword, mPage), observer);
                break;
        }
    }

    public void orderConfig(int provinceId, int cityId, String keyword) {
        mProvinceId = provinceId;
        mCityId = cityId;
        mKeyword = keyword;
        mRefreshStatus = RefreshStatus.LOAD_DEFAULT;
        mPage = 1;
        getOrder();
    }

    private class MyOnLoadingListener implements OnLoadingListener {

        @Override
        public void onRefresh() {
            mRefreshStatus = RefreshStatus.PULL_TO_REFRESH;
            mPage = 1;
            getOrder();
        }

        @Override
        public void onLoadMore() {
            mRefreshStatus = RefreshStatus.LOAD_MORE;
            mPage++;
            getOrder();
        }
    }

    public void orderSuccess() {
        getOrder();
    }

    private class MyOnItemClickListener implements OnItemClickListener {

        @Override
        public void onItemClick(RecyclerHolder holder, View view, int position) {
            Order.Data data = mAdapter.getItem(position - Constant.ITEM_POSITION_MINUS);
            Bundle extras = new Bundle();
            extras.putInt(IntentKey.BID_ID, data.getBidId());
            extras.putInt(IntentKey.ORDER_CONFIG, mOrderConfig);
            extras.putString(IntentKey.NICK_NAME, data.getNickName());
            extras.putString(IntentKey.AVATAR, data.getAvatar());
            extras.putString(IntentKey.MOBILE, data.getMobile());
            extras.putInt(IntentKey.REFUSE_STATUS, data.getRefuseStatus());
            extras.putInt(IntentKey.REFUSE_REASON, data.getRefuseReason());
            extras.putString(IntentKey.REFUSE_BAK, data.getRefuseBak());
            switch (mOrderConfig) {
                case OrderConfig.RECEIPT: {
                    switch (mState) {
                        case 0:
                            ShowActivity.showActivityForResult(getActivity(), OrderDetailActivity.class, extras,
                                    RequestCodeKey.GO_RECEIPT_QUOTE);
                            break;
                        case 1:
                            ShowActivity.showActivity(getActivity(), OrderDetailActivity.class, extras);
                            break;
                        case 2:
                            ShowActivity.showActivityForResult(getActivity(), ReceiptIssueActivity.class, extras,
                                    RequestCodeKey.GO_RECEIPT_ISSUE);
                            break;
                        case 3:
                            extras.putInt(IntentKey.ORDER_STATUS, mState);
                            extras.putInt(IntentKey.FILE_STATUS, data.getFileStatus());
                            ShowActivity.showActivityForResult(getActivity(), ReceiptBackActivity.class, extras,
                                    RequestCodeKey.GO_SIGN_RECEIVE);
                            break;
                        case 4:
                            extras.putInt(IntentKey.ORDER_STATUS, mState);
                            ShowActivity.showActivityForResult(getActivity(), ReceiptBackActivity.class, extras,
                                    RequestCodeKey.EVALUATE);
                            break;
                        case 5:
                            if(data.getAcComment() == 1) {
                                extras.putBoolean(IntentKey.IS_COMMENT, true);
                                ShowActivity.showActivity(getActivity(), OrderDetailActivity.class, extras);
                            }
                            break;
                        case 6:
                            if(data.getDisabled() == 1) {
                                extras.putBoolean(IntentKey.IS_DISABLED, true);
                                ShowActivity.showActivity(getActivity(), OrderDetailActivity.class, extras);
                            }
                            break;
                    }
                }
                break;
                case OrderConfig.SELL: {
                    switch (mState) {
                        case 0:
                            if (data.getRefuseStatus() == 1) {
                                ShowActivity.showActivityForResult(getActivity(), OrderDetailActivity.class, extras,
                                        RequestCodeKey.GO_REPUBISH_BILL);
                            } else {
                                ShowActivity.showActivity(getActivity(), OrderDetailActivity.class, extras);
                            }

                            break;
                        case 1:
                            ShowActivity.showActivityForResult(getActivity(), OrderDetailActivity.class, extras,
                                    RequestCodeKey.GO_PAY);
                            break;
                        case 2:
                            extras.putInt(IntentKey.ORDER_STATUS, mState);
                            extras.putInt(IntentKey.FILE_STATUS, data.getFileStatus());
                            ShowActivity.showActivityForResult(getActivity(), ReceiptBackActivity.class, extras,
                                    RequestCodeKey.GO_SIGN_RECEIVE);
                            break;
                        case 3:
                            if (data.getFileStatus() == 2) {
                                ShowActivity.showActivityForResult(getActivity(), SellReceiptActivity.class, extras,
                                        RequestCodeKey.GO_SIGN_RECEIVE);
                            } else if (data.getFileStatus() == 3) {
                                extras.putInt(IntentKey.ORDER_STATUS, mState);
                                extras.putInt(IntentKey.FILE_STATUS, data.getFileStatus());
                                ShowActivity.showActivity(getActivity(), ReceiptBackActivity.class, extras);
                            }
                            break;
                        case 4:
                            extras.putInt(IntentKey.ORDER_STATUS, mState);
                            ShowActivity.showActivityForResult(getActivity(), ReceiptBackActivity.class, extras,
                                    RequestCodeKey.EVALUATE);
                            break;
                        case 5:
                            if(data.getBillComment() == 1) {
                                extras.putBoolean(IntentKey.IS_COMMENT, true);
                                ShowActivity.showActivity(getActivity(), OrderDetailActivity.class, extras);
                            }
                            break;
                        case 6:
                            if(data.getDisabled() == 1) {
                                extras.putBoolean(IntentKey.IS_DISABLED, true);
                                ShowActivity.showActivity(getActivity(), OrderDetailActivity.class, extras);
                            }
                            break;
                    }
                }
                break;
            }
        }
    }

    private class MyItemButtonClickListener implements ItemButtonClickListener {

        @Override
        public void buttonClick(int clickId, int position) {
            final Order.Data data = mAdapter.getItem(position - Constant.ITEM_POSITION_MINUS);
            switch (clickId) {
                case R.id.order_headicon_iv:
                    Bundle extras = new Bundle();
                    extras.putString(IntentKey.USER_ID, String.valueOf(data.getUserId()));
                    switch (mOrderConfig) {
                        case OrderConfig.RECEIPT:
                            extras.putInt(IntentKey.FROM, 2);
                            break;
                        case OrderConfig.SELL:
                            extras.putInt(IntentKey.FROM, 1);
                    }
                    ShowActivity.showActivity(getActivity(), UserHomeActivity.class, extras);
                    break;
                case R.id.order_button_tv:
                    switch (mOrderConfig) {
                        case OrderConfig.RECEIPT: {
                            switch (mState) {
                                case 4:
                                    extras = new Bundle();
                                    extras.putInt(IntentKey.BID_ID, data.getBidId());
                                    extras.putInt(IntentKey.ORDER_CONFIG, mOrderConfig);
                                    ShowActivity.showActivityForResult(getActivity(), EvaluateActivity.class, extras,
                                            RequestCodeKey.EVALUATE);
                                    break;
                            }
                        }
                        break;
                        case OrderConfig.SELL: {
                            switch (mState) {
                                case 1: {
                                    if (!data.isCanPay()) {
                                        showToastMsg("身份证和行驶证照片未上传，不能进行支付！");
                                        return;
                                    }
                                    extras = new Bundle();
                                    extras.putInt(IntentKey.CITY, data.getCityId());
                                    extras.putInt(IntentKey.PROVINCE, data.getProvinceId());
                                    extras.putInt(IntentKey.INSURANCE_COMPANY, data.getCompanyId());
                                    extras.putString(IntentKey.PLATE_NO, data.getPlateNo());
                                    extras.putString(IntentKey.TOTAL_MONEY, data.getTotalMoney());
                                    extras.putInt(IntentKey.BID_ID, data.getBidId());
                                    ShowActivity.showActivityForResult(getActivity(), PayOrderActivity.class, extras,
                                            RequestCodeKey.GO_PAY);
                                }
                                break;
                                case 2: {
                                    //0-未出单 1-已出单待签收 2-已签收待回单 3已回单待确认 4确认收到回单
                                    final int fileStatus = data.getFileStatus();
                                    final int bidId = data.getBidId();
                                    new AlertView(getActivity(), null, "请确认保单已经签收？", getString(R.string.cancel),
                                            new String[]{getString(R.string.confirm)}, null, AlertView.Style.Alert,
                                            new OnAlertItemClickListener() {
                                                @Override
                                                public void onItemClick(AlertView alertView, int position) {
                                                    switch (position) {
                                                        case 0:
                                                            confirmFile(bidId, fileStatus);
                                                            break;
                                                    }
                                                }
                                            }).show();
                                }
                                break;
                                case 4:
                                    extras = new Bundle();
                                    extras.putInt(IntentKey.BID_ID, data.getBidId());
                                    extras.putInt(IntentKey.ORDER_CONFIG, mOrderConfig);
                                    ShowActivity.showActivityForResult(getActivity(), EvaluateActivity.class, extras,
                                            RequestCodeKey.EVALUATE);
                                    break;
                            }
                        }

                        break;
                    }
                    break;
            }
        }

        private void confirmFile(int bidId, int fileStatus) {
            if (fileStatus == 0) {
                CommonUtil.showToast(getActivity(), "请等待收单方出单");
                return;
            }
            if (fileStatus == 1) {
                RetroSubscrube.getInstance().postSubscrube(AppUrl.FILE_CONFIRM, PostParam.fileConfirm(mToken, bidId, 2),
                        new BaseObserver(getActivity(), getString(R.string.loading_submit)) {
                            @Override
                            protected void onHandleSuccess(Object data, String msg) {
                                CommonUtil.showToast(getActivity(), msg);
                                MainActivity.OrderCallBack orderCallBack =
                                        ((MainActivity) getActivity()).getOrderCallBack();
                                if (orderCallBack != null) {
                                    orderCallBack.signReceiveSuccess();
                                }
                            }
                        });
            }
        }
    }

}
